﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using DVK.SP2007.Constants;

namespace DVK.SP2007
{
    /// <summary>
    /// Manages access to Organisation Recipients list.
    /// </summary>
    public class OrganisationRecipientsRepository
    {
        private SPWeb _web;

        /// <summary>
        /// Initializes a new instance of the <see cref="OrganisationRecipientsManager"/> class.
        /// </summary>
        /// <param name="web">The web.</param>
        public OrganisationRecipientsRepository(SPWeb web)
        {
            _web = web;
        }

        /// <summary>
        /// Finds the recipient by organisation code and person code.
        /// </summary>
        /// <param name="organisationCode">The organisation code.</param>
        /// <param name="personCode">The person code.</param>
        /// <returns>recipient or null, if not found</returns>
        public SPListItem FindRecipient(string organisationCode, string personCode)
        {
            var recipientsList = _web.GetListFromUrl(Urls.ListDvkMessageRecipients);
            SPQuery query = new SPQuery();
            query.RowLimit = 1;
            query.Query = "<Where><And>" +
                            "<Eq><FieldRef Name='" + Fields.RecipientOrganisationCode.Name + "' /><Value Type='Text'>" + organisationCode + "</Value></Eq>" +
                            "<Eq><FieldRef Name='" + Fields.RecipientPersonCode.Name + "' /><Value Type='Text'>" + personCode + "</Value></Eq>" +
                            "</And></Where>";
            SPListItemCollection items = recipientsList.GetItems(query);

            if (items.Count == 0)
            {
                return null;
            }

            //Extract information from the recipient
            return items[0] as SPListItem;
        }

        /// <summary>
        /// Gets the organisation recipients by organisation code.
        /// <remarks>
        /// Max 100 recipients are returned (RowLimit).
        /// </remarks>
        /// </summary>
        /// <param name="organisationCode">The organisation code.</param>
        public SPListItemCollection GetOrganisationRecipients(string organisationCode)
        {
            var recipientsList = _web.GetListFromUrl(Urls.ListDvkMessageRecipients);
            SPQuery query = new SPQuery();
            query.RowLimit = 100;
            query.Query = string.Format(
                            @"<Where>
                                <Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq>
                            </Where>",
                            Fields.RecipientOrganisationCode.Name,
                            organisationCode);
            SPListItemCollection items = recipientsList.GetItems(query);
            return items;
        }

        /// <summary>
        /// Adds the new organisation recipient.
        /// </summary>
        public void AddNewOrganisationRecipient(
                    string personCode, string organisationCode, string firstName, 
                    string surName, string email, string jobTitle, 
                    string department, string workPhone)
        {
            if (FindRecipient(organisationCode, personCode) != null)
                throw new DvkException(string.Format("Recipient with personal code: {0} and organisation code: {1} already exists.", personCode, organisationCode));
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPList recipientsList = _web.GetListFromUrl(Urls.ListDvkMessageRecipients);

                SPListItem newOrganisationPerson = recipientsList.Items.Add();
                newOrganisationPerson[Fields.RecipientPersonCode.Name] = personCode;
                newOrganisationPerson[Fields.RecipientOrganisationCode.Name] = organisationCode;
                newOrganisationPerson[Fields.FirstName.Name] = firstName;
                newOrganisationPerson[Fields.SurName.Name] = surName;

                //optional values
                newOrganisationPerson[Fields.Email.Name] = email;
                newOrganisationPerson[Fields.JobTitle.Name] = jobTitle;
                newOrganisationPerson[Fields.Department.Name] = department;
                newOrganisationPerson[Fields.WorkPhone.Name] = workPhone;

                newOrganisationPerson.Update();
            });
        }
    }
}